package com.hongyi.interceptor;


import com.hongyi.annotation.Token;
import com.hongyi.util.JacksonUtil;
import com.hongyi.util.JwtUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HongYi
 * 前端拦截器调用时，若token快要过期，则获取后端新生成的token并存储起来
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {


    @SneakyThrows
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object obj) {

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");

        // 用于响应
        Map<String, Object> responseMap = new HashMap<>(3);

        // 若目标方法不是Controller方法或方法上没有标记@Token注解，则直接放行
        if (this.isNotHandleMethod(obj) || this.isNoMarkTokenAnnotation(obj)) {
            return true;
        }

        // 获取token
        String token = this.getToken(req);
        if (null == token) {
            responseMap.put("code", 0);
            responseMap.put("message", "请求中未携带token或token已过期");
            PrintWriter writer = resp.getWriter();
            writer.write(JacksonUtil.format(responseMap));
            writer.close();
        }

        // 解析token
        Map<String, Object> verifyResultMap = JwtUtil.verify(token);

        // 查看当前token是否即将过期，若是则返回过期提示
        if (this.isExpireSoon(verifyResultMap)) {
            responseMap.put("code", 1);
            responseMap.put("message", "token即将在30分钟内过期，请及时更换");
            responseMap.put("data", verifyResultMap.get("newToken"));
            PrintWriter writer = resp.getWriter();
            writer.write(JacksonUtil.format(responseMap));
            writer.close();
        }

        // 放行请求
        return true;
    }

    /**
     * 判断token是否即将过期
     *
     * @param verifyResultMap token解析的结果
     * @return 若token即将过期，则返回true，否则返回false
     */
    private boolean isExpireSoon(Map<String, Object> verifyResultMap) {
        Object expireSoon = verifyResultMap.get("expireSoon");
        if (null == expireSoon) {
            throw new RuntimeException("token解析结果中丢失expireSoon标识");
        }
        return (boolean) expireSoon;
    }

    /**
     * 从请求头中获取token，若没获取成功，尝试从请求参数中获取，若均失败返回null
     *
     * @param req 请求对象
     * @return 若token存在则返回token字符串，否则返回null
     */
    private String getToken(HttpServletRequest req) {
        // 从请求头中获取token，若没获取成功，尝试从请求参数中获取，若均失败返回错误提示
        String token = req.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = req.getParameter("token");
            if (StringUtils.isBlank(token)) {
                return null;
            }
        }
        return token;
    }


    /**
     * 目标方法对象是否是Controller方法
     *
     * @param obj 目标方法对象
     * @return 若目标方法不Controller方法，则返回true
     */
    private boolean isNotHandleMethod(Object obj) {
        return !(obj instanceof HandlerMethod);
    }

    /**
     * 目标方法上是否标记了@Token注解
     *
     * @param obj 目标方法对象
     * @return 若目标方法上没有标记@Token注解，则返回true
     */
    private boolean isNoMarkTokenAnnotation(Object obj) {
        Method method = ((HandlerMethod) obj).getMethod();
        return !method.isAnnotationPresent(Token.class);
    }
}